package net.wicp.tams.common.tracer.instrumentation.impl;

import java.util.ArrayList;
import java.util.List;

import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;

@Slf4j
public class EnhanceJdbcDriver extends EnhanceSuperClass {

	public EnhanceJdbcDriver(String className) {
		super(className, "java.sql.Driver");
	}

	@Override
	public Result enhance(CtMethod method, String newMethodName) {
		try {
			pool.importPackage("net.wicp.tams.common.tracer.agent.jdbc");
			method.setBody("{ return new InstrumentedConnection($1, $proceed($$)); }", "this", newMethodName);
		} catch (Exception e) {
			return Result.getError("加强错误：" + e.getMessage());
		}
		return Result.getSuc();
	}

	@Override
	public List<CtMethod> findEnhanceMethods(CtClass cc) {
		List<CtMethod> retlist = new ArrayList<>();
		try {
			CtMethod connect = cc.getDeclaredMethod("connect",
					new CtClass[] { pool.get("java.lang.String"), pool.get("java.util.Properties") });
			if (!Modifier.isAbstract(connect.getModifiers())) {
				retlist.add(connect);
			}
		} catch (NotFoundException e) {
			log.error("方法[connect]没有找到", e);
		}
		return retlist;
	}

}
